package com.sinkingsquare.web.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.sinkingsquare.util.HttpUtil;

public abstract class AbstractFormController extends AbstractBaseController {

	@SuppressWarnings("unchecked")
	private Class clazz;
	
	public AbstractFormController() {
		this.clazz = getEmptyFormObject().getClass();
	}
	
	@SuppressWarnings("unchecked")
	public final ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String method = request.getMethod();
        if(method.equals("GET")) {
            Map model = new HashMap();
            model.put("form", getEmptyFormObject());
            return new ModelAndView(getFormView(request), model);
        }
        else if(method.equals("POST")) {
            Object form = HttpUtil.createFormBean(request, clazz);
            try {
                List<String> errors = new ArrayList<String>(3);
                validate(errors, form);
                if(errors.isEmpty()) {
                    doSubmit(form);
                    response.sendRedirect(getSuccessView(request));
                }
                else {
                    Map model = new HashMap();
                    model.put("form", form);
                    model.put("errors", errors);
                    return new ModelAndView(getFormView(request), model);
                }
            }
            catch(Exception e) {
                // display error:
                String error = convertException(e);
                Map model = new HashMap();
                model.put("error", error==null ? "未知错误" : error);
                model.put("form", form);
                return new ModelAndView(getFormView(request), model);
            }
            return null;
        }
        // not GET or POST:
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return null;
	}

	protected abstract void validate(List<String> errors, Object form);

	protected abstract String convertException(Exception e);

	protected abstract void doSubmit(Object form);

	protected abstract String getSuccessView(HttpServletRequest request);

	protected abstract String getFormView(HttpServletRequest request);

	protected abstract Object getEmptyFormObject();
	
}
